import {
    init,
    classModule,
    propsModule,
    styleModule,
    eventListenersModule,
    h,
} from "snabbdom/build/index.js";

const patch = init([
    classModule,
    propsModule,
    styleModule,
    eventListenersModule,
])

let app = document.querySelector('#app')
let vnode
let sortBy = ''
let totalHeight = 0
let margin = 8

let movies = [
    {
        rank: 3,
        title: 'Fight Club',
        des: 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they from an underground fight club that evolves into something much,much more...',
        elHeight: 0
    },
    {
        rank: 2,
        title: 'The Good,the Bad and the Ugly',
        des: 'A bounty hunting scan joins two men in an uneasy alliance against a third in a race to find a fortune in gold buried in a remote cemetery.',
        elHeight: 0
    },
    {
        rank: 1,
        title: '12 Angry Men',
        des: 'A dissenting juror in a murder trial slowly manages to convince the others that case is not as obviously cleat as it seemed in court.',
        elHeight: 0
    }
]

// 重新渲染
function render() {
    movies = movies.reduce((acc, m) => {
        const last = acc[acc.length - 1];
        m.offset = last ? last.offset + last.elHeight + margin : margin
        return acc.concat(m);
    }, []);
    totalHeight =
        movies.length === 0
            ? 0
            : movies[movies.length - 1].offset + movies[movies.length - 1].elHeight;
    console.log(movies)
    vnode = patch(vnode, initView(movies))
}

// 处理 movies 集合的节点
function viewMovies(movies) {
    const lis = movies.map(item => h('li.movieCard', {
        key: item.rank,
        style: {
            opacity: "0",
            transform: "translate(-200px)",
            delayed: { transform: `translateY(${item.offset}px)`, opacity: "1" },
            remove: {
                opacity: "0",
                transform: `translateY(${item.offset}px) translateX(200px)`,
            },
        },
        hook: {
            insert: (vnode) => {
                item.elHeight = vnode.elm.offsetHeight
            },
        },
    }, [
        h('span.rank', item.rank),
        h('span.title', item.title),
        h('span.des', item.des),
        h('span.delete', {
            on: {
                click: () => {
                    removeMovie(item)
                }
            }
        }, 'x')
    ]))
    return h('ul#movieCards', { style: { height: totalHeight + "px" } }, lis)
}

// 初始化整个根节点
function initView() {
    return h('div#movies.movies', [
        h('h1#title', 'Top 10 movies'),
        h('div#operate', [
            h('span#sort', 'Sort by:'),
            h('button#sortRank', {
                class: {active: sortBy === "rank"},
                on: {
                    click: () => {
                        sort('rank')
                    }
                }
            }, 'Rank'),
            h('button#sortTitle', {
                class: {active: sortBy === "title"},
                on: {
                    click: () => {
                        sort('title')
                    }
                }
            }, 'Title'),
            h('button#sortDes', {
                class: {active: sortBy === "des"},
                on: {
                    click: () => {
                        sort('des')
                    }
                }
            }, 'Description'),
            h('button#add', {
                on: {
                    click: () => {
                        addMovie()
                    }
                }
            }, 'Add')
        ]),
        viewMovies(movies)
    ])
}

// 删除 movie
function removeMovie(movie) {
    movies = movies.filter(item => item.rank !== movie.rank)
    render()
}

// 排序
function sort(type) {
    sortBy = type
    movies.sort((a, b) => {
        return type === 'rank' ? a[type] - b[type] : a[type].localeCompare(b[type])
    })

    render()
}

// 添加
function addMovie() {
    let rank = 0
    movies.forEach(movie => {
        rank = Math.max(rank, movie.rank)
    })

    movies.unshift({
        rank: ++rank,
        title: `Title_${rank}`,
        des: `我是新增的条目，是第${rank}条`,
        elHeight: 0
    })

    render()
    render()
}

// 初始化vnode
vnode = patch(app, initView())
render()


